package com.adingxiong.cft.kafka;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.serialization.StringDeserializer;

import java.time.Duration;
import java.util.Arrays;
import java.util.Properties;

/**
 * @ClassName ConsumerTest
 * @Description TODO
 * @Author xiongchao
 * @Date 2021/3/19 16:04
 **/
public class ConsumerTest {

    public static void main(String[] args) {

        Properties props = new Properties();

        props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,"192.168.10.101:9092");
        //序列化key
        props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG,StringDeserializer.class.getName());
        //序列化value
        props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,StringDeserializer.class.getName());
        // 自动offset
        props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG,true);
        // 分组
        props.put(ConsumerConfig.GROUP_ID_CONFIG,"1205");

        KafkaConsumer<String,String> consumer = new KafkaConsumer<String, String>(props);
        //订阅主题
        consumer.subscribe(Arrays.asList("test"));

        while (true) {
            ConsumerRecords<String,String> records = consumer.poll(Duration.ofSeconds(100));
            for(ConsumerRecord<String,String> str : records) {
                System.out.println(String.format("topic = %s, offset= %s ,value= %s",str.topic(),str.offset(),str.value()));
            }
            consumer.commitAsync();
        }


    }

}
